import os
import tkinter as tk
from tkinter import filedialog, messagebox
from PyPDF2 import PdfMerger

class PDFMergerApp:
    def __init__(self, root):
        self.root = root
        self.root.title("PDF合并工具")
        
        # 设置窗口大小和位置
        self.root.geometry("1024x600")
        
        # 创建UI组件
        self.create_widgets()
    
    def create_widgets(self):
        # 顶部按钮框架
        btn_frame = tk.Frame(self.root)
        btn_frame.pack(pady=10, fill=tk.X)
        
        # 选择文件按钮
        self.btn_select_files = tk.Button(
            btn_frame, 
            text="选择PDF文件", 
            command=self.select_files
        )
        self.btn_select_files.pack(side=tk.LEFT, padx=5)
        
        # 选择目录按钮
        self.btn_select_dir = tk.Button(
            btn_frame, 
            text="选择PDF目录", 
            command=self.select_directory
        )
        self.btn_select_dir.pack(side=tk.LEFT, padx=5)
        
        # 删除选中文件按钮
        self.btn_remove = tk.Button(
            btn_frame,
            text="删除选中文件",
            command=self.remove_selected,
            bg="red",
            fg="white"
        )
        self.btn_remove.pack(side=tk.LEFT, padx=5)
        
        # 文件列表显示框架
        list_frame = tk.Frame(self.root)
        list_frame.pack(pady=5, fill=tk.BOTH, expand=True, padx=10)
        
        # 文件列表标签
        self.lbl_files = tk.Label(list_frame, text="已选文件:")
        self.lbl_files.pack(anchor=tk.W)
        
        # 文件列表框和滚动条
        self.listbox_frame = tk.Frame(list_frame)
        self.listbox_frame.pack(fill=tk.BOTH, expand=True)
        
        self.scrollbar = tk.Scrollbar(self.listbox_frame)
        self.scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        
        self.file_list = tk.Listbox(
            self.listbox_frame,
            yscrollcommand=self.scrollbar.set,
            selectmode=tk.EXTENDED
        )
        self.file_list.pack(fill=tk.BOTH, expand=True)
        
        self.scrollbar.config(command=self.file_list.yview)
        
        # 输出文件名输入框架
        output_frame = tk.Frame(self.root)
        output_frame.pack(pady=5, fill=tk.X, padx=10)
        
        self.lbl_output = tk.Label(output_frame, text="输出文件名:")
        self.lbl_output.pack(anchor=tk.W)
        
        self.entry_output = tk.Entry(output_frame)
        self.entry_output.pack(fill=tk.X, pady=5)
        self.entry_output.insert(0, "merged.pdf")
        
        # 合并按钮框架
        merge_frame = tk.Frame(self.root)
        merge_frame.pack(pady=10)
        
        self.btn_merge = tk.Button(
            merge_frame, 
            text="合并PDF", 
            command=self.merge_pdfs,
            bg="green",
            fg="white",
            padx=20
        )
        self.btn_merge.pack()
    
    def select_files(self):
        files = filedialog.askopenfilenames(
            title="选择PDF文件",
            filetypes=[("PDF文件", "*.pdf")]
        )
        if files:
            for file in files:
                if file not in self.file_list.get(0, tk.END):
                    self.file_list.insert(tk.END, file)
    
    def select_directory(self):
        directory = filedialog.askdirectory(title="选择PDF文件所在目录")
        if directory:
            pdf_files = []
            for root, _, files in os.walk(directory):
                for file in files:
                    if file.lower().endswith('.pdf'):
                        file_path = os.path.join(root, file)
                        if file_path not in self.file_list.get(0, tk.END):
                            pdf_files.append(file_path)
            
            if pdf_files:
                for file in pdf_files:
                    self.file_list.insert(tk.END, file)
            else:
                messagebox.showwarning("警告", "所选目录中没有找到PDF文件")
    
    def remove_selected(self):
        selected_indices = self.file_list.curselection()
        if not selected_indices:
            messagebox.showwarning("警告", "请先选择要删除的文件")
            return
        
        # 从后往前删除，避免索引变化问题
        for i in reversed(selected_indices):
            self.file_list.delete(i)
    
    def merge_pdfs(self):
        files = self.file_list.get(0, tk.END)
        if not files:
            messagebox.showerror("错误", "请先选择要合并的PDF文件")
            return
        
        output_name = self.entry_output.get().strip()
        if not output_name:
            messagebox.showerror("错误", "请输入输出文件名")
            return
        
        if not output_name.lower().endswith('.pdf'):
            output_name += '.pdf'
        
        try:
            merger = PdfMerger()
            
            for file in files:
                merger.append(file)
            
            # 确保输出目录存在
            output_dir = os.path.dirname(output_name)
            if output_dir and not os.path.exists(output_dir):
                os.makedirs(output_dir)
            
            merger.write(output_name)
            merger.close()
            
            messagebox.showinfo("成功", f"PDF文件已成功合并到: {output_name}")
        except Exception as e:
            messagebox.showerror("错误", f"合并PDF时出错:\n{str(e)}")

if __name__ == "__main__":
    root = tk.Tk()
    app = PDFMergerApp(root)
    root.mainloop()